package cn.wolfcode.trip.admin.filter;

import cn.wolfcode.trip.base.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class ImageFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        /**
         * 1.接收浏览器发起的请求图片路径req-->Request URL:
         * 2.http://localhost:8080/upload/112a24b5-8cfd-4c7a-a931-00c29d766800.jpeg
         * 3.再进行拼接磁盘的完整路径 "c://trip" + uri
         * 4.判断文件中是否存在该图片
         * 5.存在:调用FileUtils以byte方式读取文件再以流的方式输出响应给浏览器
         * 6.不存在:放行
         */


        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();
        File file=new File(UploadUtil.PATH,uri);
        if(file.exists()){
            response.getOutputStream().write(FileUtils.readFileToByteArray(file));
        }else {
            chain.doFilter(request,response);
        }

    }

    @Override
    public void destroy() {

    }
}
